// Copyright (c) 2019 Presto Labs Pte. Ltd.
// Author: taekwon

#include "coin2/exchange/base/api_util/auth_key.h"

#include <fstream>

#include <gtest/gtest.h>

TEST(AuthKey, constructor) {
  // test1: normal parsing.
  std::string test_account_1 = R"(
  {
    "owner": "prestoinvt05",
    "name": "view",
    "access_key": "6974",
    "secret_key": "8925882",
    "generated": "49105",
    "generated_human": "long"
  })";
  std::ofstream of_1("test_account_1.json");
  of_1 << test_account_1;
  of_1.close();

  auto key_1 = AuthKey::FromFile("test_account_1.json");
  EXPECT_EQ(key_1.owner(), "prestoinvt05");
  EXPECT_EQ(key_1.key_name(), "view");
  EXPECT_EQ(key_1.access_key(), "6974");
  EXPECT_EQ(key_1.secret_key(), "8925882");
  EXPECT_EQ(key_1.generated(), "49105");
  EXPECT_EQ(key_1.generated_human(), "long");

  // test2: missing generated related fields.
  std::string test_account_2 = R"(
  {
    "owner": "prestoinvt07",
    "name": "trade",
    "access_key": "7469",
    "secret_key": "5882892",
    "others": "password"
  })";
  std::ofstream of_2("test_account_2.json");
  of_2 << test_account_2;
  of_2.close();

  auto key_2 = AuthKey::FromFile("test_account_2.json");
  EXPECT_EQ(key_2.owner(), "prestoinvt07");
  EXPECT_EQ(key_2.key_name(), "trade");
  EXPECT_EQ(key_2.access_key(), "7469");
  EXPECT_EQ(key_2.secret_key(), "5882892");
  EXPECT_EQ(key_2.generated(), "");
  EXPECT_EQ(key_2.generated_human(), "");
  EXPECT_FALSE(key_2.GetValue("non-existed"));
  auto existed_others = key_2.GetValue("others");
  EXPECT_TRUE(existed_others);
  EXPECT_EQ(existed_others.value(), "password");

  // test3: parse error.
  EXPECT_THROW(
      {
        std::string test_account_3 = R"(
    {
      "owner": "prestoinvt07",
      "name": "trade",
      "access_key": "7469",
      "secret_key": "5882892",,,,,
    })";
        std::ofstream of_3("test_account_3.json");
        of_3 << test_account_3;
        of_3.close();
        auto key_3 = AuthKey::FromFile("test_account_3.json");
      },
      std::exception);

  // test4: no file
  EXPECT_THROW(
      {
        std::string missing_file = "missing_file_t1s1t.json";
        remove(missing_file.c_str());
        auto key_4 = AuthKey::FromFile(missing_file);
      },
      std::runtime_error);

  // clean up
  remove("test_account_1.json");
  remove("test_account_2.json");
  remove("test_account_3.json");
}
